package com.yuqing.sentimentapp.home.fragment;

import android.app.Dialog;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.linkface.baselibrary.utils.DensityUtil;
import com.linkface.baselibrary.utils.StatusBarUtil;
import com.linkface.common.adaper.CommonViewHolder;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseFragment;
import com.yuqing.sentimentapp.event.CommonEvent;
import com.yuqing.sentimentapp.event.IssuedEvent;
import com.yuqing.sentimentapp.home.acitivity.NewsDetailActivity;
import com.yuqing.sentimentapp.home.acitivity.SpecialTopicDetailActivity;
import com.yuqing.sentimentapp.home.adapter.RecommendAdapter;
import com.yuqing.sentimentapp.home.bean.RecommendDataBean;
import com.yuqing.sentimentapp.home.presenter.RecommendPresenter;
import com.yuqing.sentimentapp.home.presenter.impl.RecommendPresenterImpl;
import com.yuqing.sentimentapp.home.view.RecommendView;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.utils.KeyBoardUtils;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.widget.dialog.TipsTwoBtnDialog;
import com.yuqing.sentimentapp.widget.jzvideo.Jzvd;
import com.yuqing.sentimentapp.widget.xrecyclerview.XRecyclerView;
import com.yuqing.sentimentapp.yqlist.IssuedHelper;
import com.yuqing.sentimentapp.yqlist.activity.YQReportActivity;
import com.yuqing.sentimentapp.yqlist.activity.YuQingDetailActivity;
import com.yuqing.sentimentapp.yqlist.bean.YqReplyResultBean;
import com.yuqing.sentimentapp.yqlist.bean.YqReportResultBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 推荐页
 * Created by ShenHe on 2019/4/11.
 */

public class RecommendFragment extends BaseFragment implements RecommendView<RecommendDataBean> {

    @BindView(R.id.recyclerView)
    XRecyclerView mRecyclerView;
    @BindView(R.id.editTextBodyLl)
    RelativeLayout mEditTextBodyLl;
    @BindView(R.id.et_reply)
    EditText mEtReply;
    @BindView(R.id.btn_send)
    Button mBtnSend;
    private RecommendAdapter mAdapter;
    private List<RecommendDataBean.DataBean> dataList = new ArrayList<>();
    private RecommendPresenter mPresenter;
    private int page = 1;
    private String replyContent;
    private int replyPos;
    private int currentKeyboardH;
    private int screenHeight;
    private int editTextBodyHeight;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_recommend;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initRecyclerView();
        initListener();
        setViewTreeObserver();
    }

    private void initListener() {
        EventBus.getDefault().register(this);
        mEditTextBodyLl.setOnClickListener((v) -> {
            if (mEditTextBodyLl.getVisibility() == View.VISIBLE) {
                updateEditTextBodyVisible(View.GONE, -1);
            }
        });
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setLoadingMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(true);

        mAdapter = new RecommendAdapter(getActivity(), dataList, new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                RecommendDataBean.DataBean dataBean = dataList.get(position - 1);
                if (TextUtils.equals("1", dataBean.getIsTop())) {//置顶
                    NewsDetailActivity.start(getActivity(), dataBean.getId(), dataBean.getTitle(), false);
                } else if (TextUtils.equals("N", dataBean.getType())) { //新闻
                    NewsDetailActivity.start(getActivity(), dataBean.getId(), dataBean.getTitle(), false);
                } else if (TextUtils.equals("Z", dataBean.getType())) {//即时专题
                    SpecialTopicDetailActivity.start(getActivity(), dataBean.getId(), dataBean.getTitle());
                } else if (TextUtils.equals("F", dataBean.getType())) {//专题分析
                    NewsDetailActivity.start(getActivity(), dataBean.getId(), dataBean.getTitle(), true, true);
                } else {
                    YuQingDetailActivity.start(getActivity(), dataBean.getBdArticleId(), position - 1);
                }
                dataList.get(position - 1).setIsRead("1");
                mAdapter.notifyItemChanged(position);
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        });

        mAdapter.setBottomBtnClickListener(new RecommendAdapter.RecommendBottomBtnClickListener() {
            @Override
            public void replyClickListener(int position) {
                if (mEditTextBodyLl.getVisibility() == View.GONE) {
                    updateEditTextBodyVisible(View.VISIBLE, position);
                }
            }

            @Override
            public void reportClickListener(int position) {
                RecommendDataBean.DataBean dataBean = dataList.get(position);
                String replyId = dataBean.getReplyId();
                if (TextUtils.isEmpty(replyId)) {//上报
                    LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
                    String deptLevel = "";
                    if (user != null && user.getDeptVo() != null) {
                        deptLevel = user.getDeptVo().getDeptLevel();
                        /**
                         * 总队身份，并且subReplyId不为空，显示上报，但需要把内容引用过去
                         * state=0为上报， state=1为重报
                         * replyId不为空，则去请求接口，拉取数据
                         */
                        if (!TextUtils.isEmpty(deptLevel) && TextUtils.equals(deptLevel, "1")) {
                            YQReportActivity.start(getActivity(), dataBean.getBdArticleId(), dataBean.getTitle(), dataBean.getUrl(), dataBean.getContent(), dataBean.getSubReplyId(), position, 0);
                            return;
                        }
                    }
                    YQReportActivity.start(getActivity(), dataBean.getBdArticleId(), dataBean.getTitle(), dataBean.getUrl(), dataBean.getContent(), position, 0);
                } else { //重报
                    /**
                     * state=0为上报， state=1为重报
                     * replyId不为空，则去请求接口，拉取数据
                     */
                    YQReportActivity.start(getActivity(), dataBean.getBdArticleId(), dataBean.getTitle(), dataBean.getUrl(), dataBean.getContent(), dataBean.getReplyId(), position, 1);
                }
            }

            @Override
            public void issuedClickListener(int position) {
                RecommendDataBean.DataBean dataBean = dataList.get(position);
                TipsTwoBtnDialog dialog = new TipsTwoBtnDialog(getActivity());
                dialog.setContent("确定下发这条舆情吗？");
                dialog.setTitle("下发舆情");
                dialog.setButtonListener(new TipsTwoBtnDialog.ButtonListener() {
                    @Override
                    public void buttonOkClick(Dialog dialog) {
                        IssuedHelper.getInstance(getActivity()).getIssuedPresenter().loadIssuedPrepareRequest(dataBean.getBdArticleId(), "", position);
                    }

                    @Override
                    public void buttonCancleClick(Dialog dialog) {
                    }
                });
                dialog.show();
            }

            @Override
            public void hideClickListener(int position) {
                TipsTwoBtnDialog dialog = new TipsTwoBtnDialog(getActivity());
                dialog.setContent("确定隐藏这条舆情吗？");
                dialog.setTitle("隐藏舆情");
                dialog.setButtonListener(new TipsTwoBtnDialog.ButtonListener() {
                    @Override
                    public void buttonOkClick(Dialog dialog) {
                        mPresenter.hideRequest(dataList.get(position).getBdArticleId(), position);
                    }

                    @Override
                    public void buttonCancleClick(Dialog dialog) {
                    }
                });
                dialog.show();
            }
        });

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadRecommendData(true, page);
            }

            @Override
            public void onLoadMore() {
                page++;
                loadRecommendData(false, page);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                Jzvd jzvd = view.findViewById(R.id.videoplayer);
                if (jzvd != null && Jzvd.CURRENT_JZVD != null &&
                        jzvd.jzDataSource.containsTheUrl(Jzvd.CURRENT_JZVD.jzDataSource.getCurrentUrl())) {
                    if (Jzvd.CURRENT_JZVD != null && Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                        Jzvd.resetAllVideos();
                    }
                }
            }
        });

//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    Glide.with(mContext).resumeRequests();
//                }else {
//                    Glide.with(mContext).pauseRequests();
//                }
//            }
//        });
    }

    private void setViewTreeObserver() {
        final ViewTreeObserver swipeRefreshLayoutVTO = mEditTextBodyLl.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                if (mEditTextBodyLl == null) return;
                mEditTextBodyLl.getWindowVisibleDisplayFrame(r);
                int statusBarH = StatusBarUtil.getStatusBarHeight(getActivity());//状态栏高度
                int screenH = mEditTextBodyLl.getRootView().getHeight();
                if (r.top != statusBarH) {
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                Log.d("RecommendFragment", "screenH＝ " + screenH + " &keyboardH = " + keyboardH + " &r.bottom=" + r.bottom + " &top=" + r.top + " &statusBarH=" + statusBarH);

                if (keyboardH == currentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }

                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = mEtReply.getHeight() + DensityUtil.dip2px(getActivity(), 16);

                if (keyboardH < 150) {//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE, -1);
                    return;
                }
//                //偏移listview
//                if(layoutManager!=null && commentConfig != null){
//                    layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig));
//                }
            }
        });
    }

    public void updateEditTextBodyVisible(int visibility, int position) {
        mEditTextBodyLl.setVisibility(visibility);

        if (View.VISIBLE == visibility) {
            mEtReply.requestFocus();
            //弹出键盘
            KeyBoardUtils.showSoftInput(mEtReply.getContext(), mEtReply);

            //回复
            mBtnSend.setOnClickListener(v -> {
                replyContent = mEtReply.getText().toString();
                replyPos = position;
                if (TextUtils.isEmpty(replyContent)) {
                    ToastUtil.showShort("回复内容不能为空");
                    return;
                }
                mPresenter.replyRequest(dataList.get(position).getSubReplyId(), mEtReply.getText().toString(), position);
                //隐藏回复
                if (mEditTextBodyLl.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE, -1);
                }
            });
        } else if (View.GONE == visibility) {
            //隐藏键盘
            KeyBoardUtils.hideSoftInput(mEtReply.getContext(), mEtReply);
        }
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            loadRecommendData(true, 1);
        }
    }

    private void loadRecommendData(boolean isRefresh, int page) {
        mPresenter.loadRecommendDataRequest(page, 10, isRefresh);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new RecommendPresenterImpl(this);
    }

    @Override
    public void onSuccess(RecommendDataBean data) {

    }

    @Override
    public void onFailure(String message) {
        stopLoad();
        ToastUtil.showShort(message);
    }

    /**
     * 上报、回复事件注册
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final CommonEvent event) {
        int msg = event.getMsg();
        if (msg == -1) {// 上报结果刷新
            String state = event.getState();
            int position = Integer.valueOf(state);
            YqReportResultBean object = (YqReportResultBean) event.getObject();
            if (object != null && object.getData() != null) {
                dataList.get(position).setSubStatus(object.getData().getSubStatus() == null ? "" :object.getData().getSubStatus());
                dataList.get(position).setReplyId(object.getData().getReplyId() == null ? "" : object.getData().getReplyId());// 让replyID不为空，证明已经上报过
                mAdapter.notifyItemChanged(position + 1);
            } else {
                ToastUtil.showShort("上报异常，请重试");
            }
        } else if (msg == 1) {
            String subStatus = event.getState();
            int position = (int) event.getObject();
            dataList.get(position).setSubStatus(subStatus == null ? "" :subStatus);
            mAdapter.notifyItemChanged(position + 1);
        }
    }

    /**
     * 下发事件注册
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(final IssuedEvent event) {
        int position = event.getMsg();
        String subStatus = event.getSubState();
        String pubId = event.getPubId();
        dataList.get(position).setSubStatus(subStatus == null ? "" : subStatus);
        dataList.get(position).setPubId(TextUtils.isEmpty(pubId) ? "issued success" : pubId);// 让PubId不为空，证明已经下发过
        mAdapter.notifyItemChanged(position + 1);
    }

    @Override
    public void returnRecommendResult(RecommendDataBean result, boolean isRefresh) {
        stopLoad();
        if (null == result || result.getData().size() == 0) {
            if (!isRefresh) {
                mRecyclerView.setNoMore(true);
            }
            return;
        }
        if (isRefresh) {
            dataList.clear();
        }
        dataList.addAll(result.getData());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void replySuccess(YqReplyResultBean replyResultBean, int position) {
        ToastUtil.showShort("回复成功");
        mEtReply.setText("");
        if (replyResultBean != null && replyResultBean.getData() != null) {
            YqReplyResultBean.DataBean data = replyResultBean.getData();
            String subStatus = data.getSubStatus();
            //更新舆情的下发、上报状态
            updateStatusView(subStatus, position);
        }
    }

    private void updateStatusView(String subStatus, int position) {
        dataList.get(position).setSubStatus(subStatus);
        mAdapter.notifyItemChanged(position + 1);
    }

    @Override
    public void hideSuccess(String articleId, int position) {
        if (position >= 0 && position < dataList.size()) {
            String bdArticleId = dataList.get(position).getBdArticleId();
            if (TextUtils.equals(articleId, bdArticleId)) {//双重校验
                //因为adapter中的数据比dataList中多一个
                //postion是dataList中的位置，对应adapter中位置应+1
                dataList.remove(position);
                mAdapter.notifyItemRemoved(position + 1);
            }
        }
    }

    private void stopLoad() {
        if (mRecyclerView != null) {
            mRecyclerView.refreshComplete();
            mRecyclerView.loadMoreComplete();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        IssuedHelper.getInstance(getActivity()).onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
